package com.example.musicplayer;


import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener {
    private MediaPlayer player = new MediaPlayer();
    private List<Music> data;
    private int musicId = 0;
    private ListView listView;
    private TextView tv_title;
    private TextView tv_artist;
    private RadioButton rb_play;
    private int a;
    public static Handler handler;
    private EditText et;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        local_data();
        //获取权限
        promesson();
        init();
    }

    private void promesson() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0x123);
        }
    }

    private void init() {

        player.setOnCompletionListener(new CompletionListener());
        findViewById(R.id.rb_My).setOnClickListener(this);
        findViewById(R.id.rb_Music).setOnClickListener(this);
        findViewById(R.id.rb_Find).setOnClickListener(this);
        findViewById(R.id.linear).setOnClickListener(this);
        findViewById(R.id.rb_play).setOnClickListener(this);
        findViewById(R.id.rb_next).setOnClickListener(this);
        findViewById(R.id.rb_list).setOnClickListener(this);
        tv_artist = (TextView) findViewById(R.id.tv_artist);
        tv_title = (TextView) findViewById(R.id.tv_title);
        rb_play = (RadioButton) findViewById(R.id.rb_play);
        et = (EditText) findViewById(R.id.et);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0x123:
                        handler.removeMessages(0x123);
                        playNext();
                        break;
                    case 0x124:
                        handler.removeMessages(0x124);
                        if (data.size() != 0) {
                            if (!player.isPlaying()) {
                                play(data.get(musicId));
                                player.seekTo(a);
                            } else {
                                a = player.getCurrentPosition();
                                player.stop();
                            }
                        }
                        break;
                    case 0x125:
                        handler.removeMessages(0x125);
                        musicId = msg.arg1;
                        play(data.get(msg.arg1));
                        break;
                    case 0x126:
                        handler.removeMessages(0x126);
                        Log.v("msg", msg.arg1 + "");
                        player.seekTo(msg.arg1);
                        break;

                }
            }
        };


    }

    //当播放完当前音乐时候播放下一首
    private final class CompletionListener implements MediaPlayer.OnCompletionListener {
        @Override
        public void onCompletion(MediaPlayer mp) {
            playNext();
            musicId++;
        }
    }

    //播放音乐
    private void play(Music music) {

        player.reset();
        try {
            player.setDataSource(music.getUrl());
            player.prepare();
            player.start();
            tv_title.setText(music.getTitle());
            tv_artist.setText(music.getArtist());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //下一曲
    private void playNext() {
        musicId++;
        //判断下一曲是不是为空
        if (musicId < data.size()) {
            //不为空就继续播放
            play(data.get(musicId));

        } else {
            //如果为空就把音乐ID付值为第一个
            musicId = 0;
            play(data.get(musicId));
        }
    }

    @Override
    public void onClick(View v) {

        android.app.FragmentManager manager = getFragmentManager();
        android.app.FragmentTransaction tran = manager.beginTransaction();
        switch (v.getId()) {

            case R.id.rb_My:
                Fragment_3 fragment = new Fragment_3();
                tran.replace(R.id.fragmentLayout, fragment);
                tran.commit();
                break;
            case R.id.rb_Find:
                Fragment_1 fragment_1 = new Fragment_1();
                tran.replace(R.id.fragmentLayout, fragment_1);
                tran.commit();
                break;
            case R.id.rb_Music:
                Fragment_2 fragment_2 = new Fragment_2();
                tran.replace(R.id.fragmentLayout, fragment_2);
                tran.commit();
                break;
            case R.id.linear:
                Intent intent = new Intent(MainActivity.this, MusicShows.class);
                intent.putExtra("musicId", musicId);
                intent.putExtra("a", player.getCurrentPosition());
                startActivity(intent);
                break;
            case R.id.rb_list:
                final AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                dialog.setTitle("音乐列表");
                listView = new ListView(this);
                MyAdapter adapter = new MyAdapter();
                listView.setAdapter(adapter);
                dialog.setView(listView);
                final AlertDialog alertDialog = dialog.show();
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        musicId = position;
                        play(data.get(position));
                        alertDialog.dismiss();
                    }
                });
                break;
            case R.id.rb_next:
                //下一曲
                playNext();
                break;
            //播放按钮判断
            case R.id.rb_play:
                if (data.size() != 0) {
                    if (!player.isPlaying()) {
                        play(data.get(musicId));
                        player.seekTo(a);
                        rb_play.setBackgroundResource(R.drawable.play_ctrl_pause_prs);
                    } else {
                        a = player.getCurrentPosition();
                        player.stop();
                        rb_play.setBackgroundResource(R.drawable.play_ctrl_play);
                    }
                }

                break;

        }


    }


    //获取读取内存卡权限
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    //获取读取内存卡权限
    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == 0x123) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted

            } else {
                // Permission Denied

            }
        }

    }

    //查询SD卡上的Music
    private void local_data() {
        //查询媒体数据库
        ContentResolver resolver = MainActivity.this.getContentResolver();
        /**
         * Uri：这个Uri代表要查询的数据库名称加上表的名称。
         这个Uri一般都直接从MediaStore里取得，例如我要取所有歌的信息，
         就必须利用MediaStore.Audio.Media. EXTERNAL _CONTENT_URI这个Uri。
         *
         */
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        ergodic(cursor);
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(MainActivity.this, R.layout.music_data, null);
                holder.txt_artist = (TextView) convertView.findViewById(R.id.tv_artist);
                holder.txt_title = (TextView) convertView.findViewById(R.id.tv_title);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txt_artist.setText(data.get(position).getArtist());
            holder.txt_title.setText(data.get(position).getTitle());
            return convertView;
        }

        private class ViewHolder {
            TextView txt_artist;
            TextView txt_title;
        }
    }

    private void ergodic(Cursor cursor) {
        data = new ArrayList<>();
//        cursor.moveToFirst();
        while (cursor.moveToNext()) {
            //歌曲文件的路径MediaStore.Audio.Media.DATA
            String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            //歌曲的歌手名MediaStore.Audio.Media.ARTIST
            String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
            //歌曲标题
            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));//时长
            Music music = new Music();
            music.setTime(duration);
            music.setUrl(url);
            music.setTitle(title);
            music.setArtist(artist);
            data.add(music);
        }
    }
}
